package com.fang.controller;

import cn.hutool.core.map.MapUtil;
import com.fang.common.cache.RedisCacheEnum;
import com.fang.common.wrapper.ResponseWrapper;
import com.fang.entity.SysUser;
import com.fang.util.RedisUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Fang Ruichuan
 * @date 2022-08-28 13:44
 */
@RestController
@Api(value = "权限认证", tags = "权限认证")
public class AuthController extends BaseController {

    @Autowired
    @Qualifier("captchaProducer")
    private Producer producer;

    @GetMapping("/captcha")
    @ApiOperation(value = "获取验证码")
    public ResponseWrapper captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 为了测试
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        RedisUtil.StringOps.setEx(RedisCacheEnum.CAPTCHA_KEY.getValue() + ":" + key,
                code, RedisCacheEnum.CAPTCHA_KEY.getTime(), TimeUnit.SECONDS);
        return ResponseWrapper.success(MapUtil.builder()
                .put("token", key)
                .put("captchaImg", base64Img)
                .build());
    }

    @GetMapping("/sys/userInfo")
    @ApiOperation(value = "获取用户信息")
    public ResponseWrapper userInfo(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        return ResponseWrapper.success(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("avatar", sysUser.getAvatar())
                .put("created", sysUser.getCreated())
                .build());
    }
}
